package com.hiyee.customer.controller;

import com.hiyee.api.controller.BaseController;
import com.hiyee.api.controller.customer.AuthControllerApi;
import com.hiyee.customer.service.CustomerService;
import com.hiyee.enums.LoginTypeEnum;
import com.hiyee.enums.SmsCodeSceneEnum;
import com.hiyee.idWorker.SnowflakeIdUtil;
import com.hiyee.pojo.Customer;
import com.hiyee.pojo.bo.CustomerLoginBO;
import com.hiyee.pojo.bo.GetSmsCodeBO;
import com.hiyee.response.ResponseJsonResult;
import com.hiyee.response.ResponseStatusEnum;
import com.hiyee.utils.DateTimeUtil;
import com.hiyee.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
public class AuthController extends BaseController implements AuthControllerApi {

    @Autowired
    private CustomerService customerService;
    @Autowired
    SnowflakeIdUtil snowflakeIdUtil;

    @Override
    public ResponseJsonResult getSmsCode(GetSmsCodeBO bo) {
        // 是否存在场景
        if(!SmsCodeSceneEnum.exist(bo.getScene())) {
            return ResponseJsonResult.error(ResponseStatusEnum.REQUEST_PARAM_ERROR);
        }
        // 获取验证码频率限制一分钟只能获取一次
        String smsCodeKey = bo.getScene() + "_" + bo.getMobile();
        if(redisOperator.keyIsExist("lock_" +smsCodeKey)) {
            return ResponseJsonResult.error(ResponseStatusEnum.SMS_CODE_SEND_BUSINESS);
        } else {
            // 设置频率锁
            redisOperator.setnx60s("lock_" +smsCodeKey, "1");
        }
        // 生成短信验证码
        String smsCode = String.valueOf((int)(Math.random()*900000 + 100000));
        // 存入缓存 有效期 5分钟
        redisOperator.set(smsCodeKey, smsCode, 5 * 60);
        System.out.println("[获取验证码] 当前的验证码为：" + smsCode);
        return ResponseJsonResult.success(smsCode);
    }

    @Override
    public ResponseJsonResult login(CustomerLoginBO bo) {
        // 登录方式是否存在
        if(!LoginTypeEnum.exist(bo.getLoginType())) {
            return ResponseJsonResult.error(ResponseStatusEnum.LOGIN_TYPE_NOT_FOUND);
        }
        // 根据登录类型从处理
        Customer customer = null;
        // 账户密码登录
        if(bo.getLoginType().equals(LoginTypeEnum.PWD.getValue())) {
            customer = customerService.getByUsername(bo.getUsername());
            if(customer == null) {
                return ResponseJsonResult.error(ResponseStatusEnum.CUSTOMER_LOGIN_FAIL);
            }
            // todo
        }
        // 手机短信验证码登录
        if(bo.getLoginType().equals(LoginTypeEnum.SMS_CODE.getValue())) {
            customer = customerService.getByMobile(bo.getMobile());
            if(customer == null) {
                // 客户不存在则自动创建客户信息、账户信息
                customer = customerService.registerByMobile(bo.getMobile());
            }
            // 校验短信验证码
            String smsCodeKey = SmsCodeSceneEnum.LOGIN.getValue() + "_" + bo.getMobile();
            if(!redisOperator.keyIsExist(smsCodeKey)
                    || !redisOperator.get(smsCodeKey).equals(bo.getCode())) {
                return ResponseJsonResult.error(ResponseStatusEnum.SMS_CODE_ERROR);
            }
            // 删除短信验证码
            redisOperator.del(smsCodeKey);
        }
        if(customer == null) {
            return ResponseJsonResult.error(ResponseStatusEnum.CUSTOMER_LOGIN_FAIL);
        }
        System.out.println("登录：" + customer.getCustomerId());
        // 生成 token
        Map<String, Object> data = new HashMap<>();
        data.put("customerId", customer.getCustomerId());
        data.put("nickname", customer.getNickname());
        String token = JWTUtil.create(data);

        // 返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("expiredAt", DateTimeUtil.getCurrentStamp(new Date()) + JWTUtil.JWT_EXPIRED_TIME / 1000 - 10);
        result.put("customerId", customer.getCustomerId());
        result.put("nickname", customer.getNickname());
        return ResponseJsonResult.success(result);
    }
}
